package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    // 发送短信的服务对象
    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void getCode(String phone) {

        // 验证码的限制
        // 1. 手机号不为空
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        // 2. 验证码是否一分钟之内发过(过于频繁)
        Boolean result = redisTemplate.hasKey(key);

        if (result) {
            // 手机号已经反送过验证码
            // 判断是否频繁
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            Integer total = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            if (total - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        // 1. 生成随机的验证码(6位)
        String code = VerifyCodeUtil.getVerifyCode(6);
        // 2. 发送手机验证码
        smsService.senSms(phone, code);
        // 3. 将验证码信息存储到 redis
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        // 1. 判断验证码是否正确
        String code = loginVo.getCode();
        String phone = loginVo.getPhone();
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

        if (!StringUtils.hasText(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        // 2. 判断手机号...
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        // 获取redis中的验证码 （需要key）
        String redisCode = redisTemplate.opsForValue().get(key);
        if (redisCode == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if (!redisCode.equals(code)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        // 查询手机号是否注册过

        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        if (userInfo == null) {
            // 不存在 则在数据库中创建 并返回主键值给当前对象的属性(mybatisplus自动完成)
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-" + phone.substring(5));
            userInfoMapper.insert(userInfo);
        }

        // 判断用户的状态是否可以登陆
        if (userInfo.getStatus()==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
            // 登录成功 创建token
        String token = JwtUtil.createToken(phone, userInfo.getId());
        return token;
    }
}
